package com.imooc.service.impl;
import com.imooc.base.BaseInfoProperties;
import com.imooc.bo.VlogBo;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.VlogMapper;
import com.imooc.mapper.VlogMapperCustom;
import com.imooc.pojo.Vlog;
import com.imooc.service.VlogService;
import com.imooc.utils.PagedGridResult;
import com.imooc.vo.IndexVlogVO;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
public class VlogServiceImpl extends BaseInfoProperties implements VlogService  {


    @Resource
    private VlogMapper vlogMapper;
    @Resource
    private VlogMapperCustom vlogMapperCustom;
    @Autowired
    private Sid sid;

    @Transactional
    @Override
    public void createVlog(VlogBo vlogBo) {
        String vid = sid.nextShort();

        Vlog vlog = new Vlog();
        BeanUtils.copyProperties(vlogBo, vlog);

        vlog.setId(vid);

        vlog.setLikeCounts(0);
        vlog.setCommentsCounts(0);
        vlog.setIsPrivate(YesOrNo.NO.type);

        vlog.setCreatedTime(new Date());
        vlog.setUpdatedTime(new Date());
        vlogMapper.insert(vlog);
    }

    @Override
    public PagedGridResult getIndexVlogList(String search, Integer page, Integer pageSize) {
        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(search)){
            map.put("search",search);
        }
        List<IndexVlogVO> list = vlogMapperCustom.getIndexVlogList(map);
        PagedGridResult pagedGridResult = setterPagedGrid(list, page);
        return pagedGridResult;
    }

    @Override
    public IndexVlogVO getVlogDetailById(String vlogId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("vlogId",vlogId);
        List<IndexVlogVO> list = vlogMapperCustom.getVlogDetailById(map);
        if (list == null && list.size()>0 && !list.isEmpty()) {
            IndexVlogVO indexVlogVO = list.get(0);
            return indexVlogVO;
        }
        return null;
    }

    @Transactional
    @Override
    public void changeToPrivate(String userId, String vlogId,Integer yseOn) {
        Example example = new Example(Vlog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",vlogId);
        criteria.andEqualTo(" vlogerId",userId);
        Vlog vlog = new Vlog();
        vlog.setIsPrivate(yseOn);
        vlogMapper.updateByExampleSelective(vlog,example);
    }

}

